package com.king.armips.android.base;

import android.content.Context;
import android.content.Intent;

import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityOptionsCompat;
import androidx.fragment.app.Fragment;

public class ActivityLauncher implements ActivityResultCallback<ActivityResult> {

    private ActivityResultLauncher<Intent> launcher;
    private OnActivityResult onResult;
    private Context context;

    void onFragmentCreate(Fragment fragment) {
        launcher = fragment.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this);
        context = fragment.requireContext();
    }

    void onActivityCreate(ComponentActivity activity){
        launcher = activity.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), this);
        context = activity;
    }

    public void launch(@NonNull Intent intent, @Nullable OnActivityResult onResult){
        launch(intent, onResult, null);
    }

    public void launch(@NonNull Intent intent, @Nullable OnActivityResult onResult, @Nullable ActivityOptionsCompat options){
        this.onResult = onResult;
        launcher.launch(intent, options);
    }

    public Context getContext() {
        return context;
    }

    @Override
    public void onActivityResult(ActivityResult result) {
        if (onResult != null) {
            onResult.onResult(result);
        }
    }

    public interface OnActivityResult {
        void onResult(ActivityResult result);
    }

}
